import type { SystemItem, SystemFilter } from '@/types/system';
import { http } from '@/utils/http'

interface PaginationData<T = any> {
  list: T[];
  total: number;
  current_page: number;
  last_page: number;
  per_page: number;
}

export const systemApi = {
  // 获取系统列表（分页）
  async getSystemList(
    filter?: SystemFilter, 
    page: number = 1, 
    limit: number = 10,
    sortField: string = 'sort',
    sortOrder: string = 'asc'
  ): Promise<PaginationData<any>> {
    const params = new URLSearchParams();
    
    if (filter) {
      if (filter.displayStatus) params.append('displayStatus', filter.displayStatus);
      if (filter.systemTag) params.append('systemTag', filter.systemTag);
      if (filter.systemName) params.append('systemName', filter.systemName);
      if (filter.systemCode) params.append('systemCode', filter.systemCode);
    }
    
    params.append('page', page.toString());
    params.append('limit', limit.toString());
    params.append('sortField', sortField);
    params.append('sortOrder', sortOrder);

    const result = await http.get<any>('/api/system/index?'+`${params}`)
    
    if (result.code === 200 && result.data) {
      return result.data;
    } else {
      throw new Error(result.message || '获取数据失败');
    }
  },

  // 创建系统
  async createSystem(system: Omit<SystemItem, 'id'>): Promise<SystemItem> {
    const result = await http.post('/api/system/create', system);
    if (result.code === 200 && result.data) {
      return result.data;
    } else {
      throw new Error(result.message || '创建失败');
    }
  },

  // 更新系统
  async updateSystem(id:number,system: Partial<SystemItem>): Promise<SystemItem> {
    system.id = id;
    const result = await http.post('/api/system/update', system);
    if (result.code === 200 && result.data) {
      return result.data;
    } else {
      throw new Error(result.message || '更新失败');
    }
  },

  // 删除系统
  async deleteSystem(id: number): Promise<void> {
    const result = await http.post('/api/system/delete', {id:id});
    if (result.code !== 200) {
      throw new Error(result.message || '删除失败');
    }
  },

  // 获取系统详情
  async getSystemDetail(id: number): Promise<any> {
    const result = await http.get('/api/system/read?id='+id)
    if (result.code === 200 && result.data) {
      return result.data;
    } else {
      throw new Error(result.message || '获取详情失败');
    }
  },

  // 上传图标
  async uploadIcon(file: File): Promise<{ path: string; url: string }> {
    console.log(file);
    const formData = new FormData();
    formData.append('file', file);
    console.log(formData);
    const result = await http.post('/api/system/uploadIcon', formData);
    if (result.code === 200 && result.data) {
      return result.data;
    } else {
      throw new Error(result.message || '上传失败');
    }
  }
};